<template>
  <el-dialog v-model="visible" :title="title" width="600px" draggable align-center>
    <el-form ref="formRef" :model="formData" :rules="rules" class="p-2" label-width="120px" >
      <el-form-item label="支出类型" prop="expendType" >
        <el-select v-model="formData.expendType" placeholder="请选择支出类型" >
          <el-option v-for="item in getEnumBySn('ExpensesEnum')" :key="item.value" :label="item.label"
                     :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="支出金额" prop="expendValue">
        <el-input-number v-model.number="formData.expendValue" placeholder="请输入支出金额"></el-input-number>
      </el-form-item>
      <el-form-item label="支出时间" prop="expendTime">
        <el-date-picker v-model="formData.expendTime" type="datetime" placeholder="选择支出时间"
                        value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="formData.memo" placeholder="备注信息"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="confirm" :loading="confirmLoading">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
import { getEnumBySn } from "@/api/enums";

const visible = ref(false)
const title = ref("")

const formRef = ref()
const formData = ref({
  expendType: '',
  expendValue: 0,
  expendTime: '',
  memo: '',
});
const rules = {
  expendType: [
    { required: true, message: '请选择支出类型', trigger: 'change' },
  ],
  expendValue: [
    { required: true, message: '请输入支出金额', trigger: 'blur' },
  ],
  expendTime: [
    { required: true, message: '请选择支出时间', trigger: 'change' },
  ],
};
const type = ref('')

import request from '@/config/axios'

const confirmLoading = ref(false)

const emit = defineEmits(["ok"])

const confirm = () => {
  formData.value.type = 'PERSON'
  formRef.value.validate((valid) => {
    if (valid) {
      confirmLoading.value = true
      try {
        const url = {
          'add': '/studioExpenses/save',
          'bianji': '/studioExpenses/updateById',
        }
        request.post({
          url: url[type.value],
          data: formData.value
        }).then(res => {
          emit('ok')
          ElMessage.success("保存成功!")
        }).finally(() => {
          visible.value = false
        })
      } catch (error) {
        throw error;
      } finally {
        confirmLoading.value = false

      }
    }
  });

}

defineExpose({
  add: () => {
    visible.value = true
    type.value = 'add'
    formData.value = {}
  },
  edit: (rowData) => {
    console.log('------1-------', rowData)
    visible.value = true
    formData.value = rowData
    type.value = 'bianji'
  },
})

</script>

<style scoped lang="scss"></style>
